package com.health.system.action.organiza;

import static com.health.system.javacommon.util.Struts2JsonHelper.outJson;
import static com.health.system.javacommon.util.Struts2JsonHelper.outJsonString;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;
import cn.org.rapid_framework.page.Page;
import cn.org.rapid_framework.page.PageRequest;

import com.health.system.javacommon.base.BaseStruts2Action;
import com.health.system.javacommon.jquery.JqueryPageHelper;
import com.health.system.javacommon.jquery.ListRange;
import com.health.system.javacommon.util.StringTool;
import com.health.system.model.organiza.DataOrganizations;
import com.health.system.service.organiza.DataOrganizationsManager;
import com.health.system.springSecurity.LogonUser;
import com.health.system.springSecurity.UserInfo;



/**
 * Title: 组织机构(表TG_DATA_ORGANIZATIONS)_INFO Action 
 * Description: 页面通过Ajax调用Action层,返回JSONO数据
 * Copyright: Copyright (c) 2012-03 
 * Company: 
 * 
 * @author bzq 
 * @version 1.0 
*/


public class DataOrganizationsAction extends BaseStruts2Action {
	
	private DataOrganizationsManager dataorganizationsManager;
	
	/** 通过spring自动注入 */
	public void setDataOrganizationsManager(DataOrganizationsManager manager) {
		this.dataorganizationsManager = manager;
	}	
	

	
	/**
	 * jqGrid使用列表
	 * @throws IOException
	 */
	public void list() throws IOException{
		PageRequest<Map> pr = JqueryPageHelper.createPageRequestForJquery(getRequest());
		//从登录用户类中取当前用户信息,进行只能操作当前EC机构
		
//		Map mapParam = pr.getFilters();
//		mapParam.put("paramEcId", "1");
//		pr.setFilters(mapParam); 	
		Page page = dataorganizationsManager.findByPageRequest(pr);
		
		
		List<DataOrganizations> DataOrganizationslist = (List) page.getResult();
		ListRange<DataOrganizations> resultList = new ListRange<DataOrganizations>();
		resultList.setDataRows(DataOrganizationslist);
        resultList.setRecords(page.getTotalCount());
        resultList.setRows(page.getPageSize());
		if(page.getTotalCount()%page.getPageSize()>0){
			resultList.setTotal(page.getTotalCount() / page.getPageSize()+1);
		}else{
			resultList.setTotal(page.getTotalCount() / page.getPageSize());
		}
		resultList.setPage(pr.getPageNumber());
		outJson(resultList);
	}

	/**
	 * 组织机构添加
	 * @throws IOException
	 */
	public void save() throws IOException{
		Map<String, Object> result = new HashMap<String, Object>();
		try{
			HttpServletRequest request = getRequest();
			String dataorganizationsJson = request.getParameter("dataorganizationsJson");
			if (null != dataorganizationsJson&&!"".equals(dataorganizationsJson)) {
				JSONObject jsonobject =JSONObject.fromObject( dataorganizationsJson );
				DataOrganizations dataorganizationsobj = (DataOrganizations)JSONObject.toBean(jsonobject, DataOrganizations.class); 
				//从登录用户类中取当前用户信息,进行只能操作当前EC机构
				UserInfo userInfo = LogonUser.logonUser();
				/**将当前操作员机构ID设为新增的机构的上级机构ID*/
				if(null!=userInfo){
					dataorganizationsobj.setHigherId(userInfo.getCpId());
				}
				dataorganizationsManager.saveInfo(dataorganizationsobj);
				result.put("success", true);
				result.put("msg", "添加成功!");
			}else{
				result.put("success", false);
				result.put("msg", "添加失败 数据错误!");
			}
		}catch (Exception e){
			result.put("success", false);
			result.put("msg", "添加失败!");
			e.printStackTrace();
		}
		outJson(result);
	}
	
	/**
	 * 组织机构修改
	 * @throws IOException
	 */
	public void update() throws IOException{
		Map<String, Object> result = new HashMap<String, Object>();
			try{
				HttpServletRequest request = getRequest();
				String dataorganizationsJson = request.getParameter("dataorganizationsJson");
				if (null != dataorganizationsJson&&!"".equals(dataorganizationsJson)) {
					JSONObject jsonobject =JSONObject.fromObject( dataorganizationsJson );
					DataOrganizations dataorganizationsobj = (DataOrganizations)JSONObject.toBean(jsonobject, DataOrganizations.class); 
					dataorganizationsobj.setId(jsonobject.get("id").toString());
					dataorganizationsManager.update(dataorganizationsobj);
					result.put("success", true);
					result.put("msg", "修改成功!");
				}else{
					result.put("success", false);
					result.put("msg", "修改失败 数据错误!");
				}
			}catch (Exception e){
				result.put("success", false);
				result.put("msg", "修改失败!");
				e.printStackTrace();
			}
		outJson(result);
	}
	
	/**
	 * 组织机构删除
	 * @throws IOException
	 */
	public void delete() throws IOException{
		Map<String, Object> result = new HashMap<String, Object>();
		try{
			HttpServletRequest request = getRequest();
			String ids = request.getParameter("ids");
			if (null != ids&&!"".equals(ids)){
				DataOrganizations dataorganizations =new DataOrganizations();
		        //将前台传来的字符串转换成List,并映射到数据的idList属性中。
				//数据类必须定义个idList的属性来存在ID数组(java.util.ArrayList idList)。
				dataorganizations.setIdList(StringTool.stringToArray(ids));
				dataorganizationsManager.removeByIdArry(dataorganizations);
				result.put("success", true);
				result.put("msg", "删除成功");
			}else{
				result.put("success", false);
				result.put("msg", "删除失败 数据错误!");
			}
		}catch (Exception e){
			result.put("success", false);
			result.put("msg", "删除失败!");
			e.printStackTrace();
		}
		outJson(result);
	}
	
	/**
	 * 机构下拉框所用
	 * @throws IOException
	 */
	public void getDataOrganizationsComboBox() throws IOException{
		Map<String, Object> result = new HashMap<String, Object>();
		try{
			List list =null;
			String str ="<option value=\"\" selected>-请选择-</option>";
			DataOrganizations dataOrganizations=new DataOrganizations();
			//从登录用户类中取当前用户信息,进行只能操作当前EC机构
			//com.health.system.springSecurity.UserInfo userInfo = LogonUser.logonUser();
			Map map = new HashMap();
			//map.put("paramEcId", userInfo.getCpId());
			list = dataorganizationsManager.findList(map);
			for (int i = 0; list != null && i < list.size(); i++) {
				dataOrganizations = (DataOrganizations)list.get(i);
				str += "<option value=\"" + dataOrganizations.getId() + "\">" + dataOrganizations.getCpName() + "</option>";
			}
			result.put("success", true);
			result.put("msg", str);
		}catch (Exception e){
			result.put("success", false);
			result.put("msg", "");
			e.printStackTrace();
		}
		outJson(result);
	}
	
	/**
	 * EC下机构下拉框所用
	 * @throws IOException
	 */
	public void getECDataOrganizationsComboBox() throws IOException{
		Map<String, Object> result = new HashMap<String, Object>();
		try{
			List list =null;
			String str ="";
			Map ecmap = new HashMap();
			//UserInfo userInfo = LogonUser.logonUser();
			ecmap.put("cpNature", "3");
			//ecmap.put("paramEcId", userInfo.getCpId());
			DataOrganizations dataOrganizations=new DataOrganizations();
			list = dataorganizationsManager.findList(ecmap);
			for (int i = 0; list != null && i < list.size(); i++) {
				dataOrganizations = (DataOrganizations)list.get(i);
				str += "<option value=\"" + dataOrganizations.getId() + "\">" + dataOrganizations.getCpName() + "</option>";
			}
			result.put("success", true);
			result.put("msg", str);
		}catch (Exception e){
			result.put("success", false);
			result.put("msg", "");
			e.printStackTrace();
		}
		outJson(result);
	}
	
	
	/**
	 * 机构下拉树(刘文辉)
	 * @throws IOException
	 */
	public void getDataOrganizationsTree() throws IOException {
		
		String result="",id="",parentId="",name="";
        Map subMp = new HashMap();
        List sublist = new ArrayList();

        DataOrganizations data = new DataOrganizations();
		//从登录用户类中取当前用户信息,进行只能操作当前EC机构
		//com.health.system.springSecurity.UserInfo userInfo = LogonUser.logonUser();
		Map param = new HashMap();
		//param.put("paramEcId", userInfo.getCpId());
		List dataList =dataorganizationsManager.findList(param);

		
		HttpServletRequest request = getRequest();
		Map<String, Object> results = new HashMap<String, Object>();
		try{
			int dataListsize= dataList.size();
			for (int i = 0; dataList != null && i < dataListsize; i++) {
				data = (DataOrganizations)dataList.get(i);
				id=data.getId();
				parentId=data.getHigherId();
				name=data.getCpName();
				if(parentId.equals("0")){
					if(result==""){
						result ="{name:'"+name+"',pId:'"+parentId+"',id:'"+id+"'}";
	            	}else{
						result +=",{name:'"+name+"',pId:'"+parentId+"',id:'"+id+"'}";
	            	}
					subMp.put(id, name);
				}else{
	            	sublist.add(data);
				}
			}
			if(sublist.size()>0){
	        	result=getSubTree(sublist,subMp,result);
	        }
			results.put("success", true);
			results.put("msg", "["+result+"]");
		}catch (Exception e){
			results.put("success", false);
			results.put("msg", "");
			e.printStackTrace();
		}
		outJson(results);
	}
	/**
	 * 拼树字符串
	 * @param sublist
	 * @param subMp
	 * @param result
	 * @return
	 * @author bzq
	 */
	private String getSubTree(List sublist,Map subMp,String result) {
		String id="",parentId="",name="";
		DataOrganizations data = new DataOrganizations();
		Map Mp = new HashMap();
        List slist = new ArrayList();
        
        for (int i = 0; i < sublist.size(); i++) { //遍历所有子节点
        	data = (DataOrganizations)sublist.get(i);
        	id=data.getId();
			parentId=data.getHigherId();
			name=data.getCpName();
			
			if(subMp.containsKey(parentId)){
	            String tmpstr="",tmpstr1="",tmpstr2="",tmpstr3="";
	            tmpstr  ="{name:'"+name+"',pId:'"+parentId+"',id:'"+id+"'}";
	            Mp.put(id, name);
	            if(result.indexOf("id:'"+parentId+"',open:false")!=-1){
	    			tmpstr1 =result.substring(0,result.indexOf("id:'"+parentId+"',open:false"));
	    			String str =result.substring(result.indexOf("id:'"+parentId+"',open:false"),result.length());
	    			tmpstr1 +=str.substring(0, str.indexOf("}")+1);
	    			tmpstr2 =","+tmpstr;
	    			tmpstr3 =str.substring(str.indexOf("}")+1,str.length());
	    		}else{
	    			tmpstr1 =result.substring(0,result.indexOf("id:'"+parentId+"'")+("id:'"+parentId+"'").length());
	        		tmpstr2 =",open:false},"+tmpstr;
	        		tmpstr3 =result.substring(result.indexOf("id:'"+parentId+"'")+("id:'"+parentId+"'").length()+1,result.length());
	    		}
	    		result =tmpstr1+tmpstr2+tmpstr3;
	        }else{
	        	slist.add(data);
        	}
        }
        if(slist.size()>0){
        	result=getSubTree(slist,Mp,result);
        }
		return result;
	}
	
	/**
	 * 本用户所管辖机构下拉树(刘文辉)
	 * @throws IOException
	 */
	public void userDataOrganizationsTree() throws IOException {
		
		String result="",id="",parentId="",name="";
        Map subMp = new HashMap();
        List sublist = new ArrayList();

        DataOrganizations data = new DataOrganizations();
		HttpServletRequest request = getRequest();
		
		try{
			String userName = request.getParameter("userName");
			Map param = new HashMap();
			param.put("cpName", userName);
			List dataList =dataorganizationsManager.userDataOrganizationsTree(param);
			
			int dataListsize= dataList.size();
			for (int i = 0; dataList != null && i < dataListsize; i++) {
				data = (DataOrganizations)dataList.get(i);
				id=data.getId();
				parentId=data.getHigherId();
				name=data.getCpName();
				result ="{name:'"+name+"',checked:true,id:'"+id+"'}";
				subMp.put(id, name);
				
				param.clear();
				param.put("higherId", id);
				sublist=dataorganizationsManager.findList(param);
			}

			if(sublist.size()>0){
	        	result=getDataSubTree(sublist,subMp,result);
	        }
		}catch (Exception e){
			result="";
			e.printStackTrace();
		}
		outJsonString( "["+result+"]");
	}
	
	/**
	 * 
	 * @param sublist
	 * @param subMp
	 * @param result
	 * @return
	 */
	
	private String getDataSubTree(List sublist,Map subMp,String result) {
		String id="",parentId="",name="";
		DataOrganizations data = new DataOrganizations();
		Map Mp = new HashMap();
        List slist = new ArrayList();
        
        int sublistSize =sublist.size();
        for (int i = 0; i < sublistSize; i++) { //遍历所有子节点
        	data = (DataOrganizations)sublist.get(i);
        	id=data.getId();
			parentId=data.getHigherId();
			name=data.getCpName();
			
			if(subMp.containsKey(parentId)){
	            String tmpstr="",tmpstr1="",tmpstr2="",tmpstr3="";
	            	tmpstr ="{name:'"+name+"',id:'"+id+"'}";
	            if(result.indexOf("id:'"+parentId+"',nodes")!=-1){
	    			tmpstr1 =result.substring(0,result.indexOf("id:'"+parentId+"',nodes"));
	    			String str =result.substring(result.indexOf("id:'"+parentId+"',nodes"),result.length());
	    			tmpstr1 +=str.substring(0, str.indexOf("]"));
	    			tmpstr2 =","+tmpstr;
	    			tmpstr3 =str.substring(str.indexOf("]"),str.length());
	    		}else{
	    			tmpstr1 =result.substring(0,result.indexOf("id:'"+parentId+"'")+("id:'"+parentId+"'").length());
	        		tmpstr2 =",nodes:["+tmpstr+"]";
	        		tmpstr3 =result.substring(result.indexOf("id:'"+parentId+"'")+("id:'"+parentId+"'").length(),result.length());
	    		}
	    		result =tmpstr1+tmpstr2+tmpstr3;
	    		Mp.put(id, name);
	    		
	    		Map param = new HashMap();
	    		param.put("higherId", id);
	    		slist=dataorganizationsManager.findList(param);
	    		
	    		if(slist.size()>0){
	            	result=getDataSubTree(slist,Mp,result);
	            }
	        }
        }
        
		return result;
	}
	
	
	/**
	 * 组织机构分配(刘文辉)
	 * @throws IOException
	 */
	public void getDataAllTree() throws IOException {
		
		String result="",id="",parentId="",name="";
		Map mmsMp = new HashMap();
        Map subMp = new HashMap();
        List sublist = new ArrayList();
        
        Hashtable dataAccesshsh = new Hashtable(); 
        DataOrganizations data = new DataOrganizations();
        //DataAccessPermission dataAccessPn = new DataAccessPermission(); 
		
		List dataList = null;
		List dataAccessList = null;
		
		HttpServletRequest request = getRequest();
		try{
			String mainStructureId = request.getParameter("mainStructureId"); //组织ID

			Map map = new HashMap();
			if (mainStructureId!=null && !"".equals(mainStructureId)) {
				map.put("mainStructureId", mainStructureId);
			}else {
				throw new Exception("参数错误 组织ID为空!");
			}

			dataList = dataorganizationsManager.findAll();
			

			for (int i = 0; dataList != null && i < dataList.size(); i++) {
				data = (DataOrganizations)dataList.get(i);
				id=data.getId();
				parentId=data.getHigherId();
				name=data.getCpName();
				if(parentId.equals("0")){
					if(result==""){
						if(dataAccesshsh.containsKey(id)){
							result ="{name:'"+name+"',checked:true,id:'"+id+"'}";
						}else{
							result ="{name:'"+name+"',id:'"+id+"'}";
						}
	            	}else{
	            		if(dataAccesshsh.containsKey(id)){
							result +=",{name:'"+name+"',checked:true,id:'"+id+"'}";
						}else{
							result +=",{name:'"+name+"',id:'"+id+"'}";
						}
	            	}
					mmsMp.put(id, name);
				}else{
	            	sublist.add(data);
				}
			}
			if(sublist.size()>0){
	        	result=getSubAllTree(sublist,mmsMp,dataAccesshsh,result);
	        }
		}catch (Exception e){
			result="";
			e.printStackTrace();
		}
		outJsonString("["+result+"]");
	}
	
	private String getSubAllTree(List sublist,Map subMp,Map dataAccesshsh,String result) {
		String id="",parentId="",name="";
		DataOrganizations data = new DataOrganizations();
		Map Mp = new HashMap();
        List slist = new ArrayList();
        
        int sublistSize=sublist.size();
        for (int i = 0; i < sublistSize; i++) { //遍历所有子节点
        	data = (DataOrganizations)sublist.get(i);
        	id=data.getId();
			parentId=data.getHigherId();
			name=data.getCpName();
			
			if(subMp.containsKey(parentId)){
	            String tmpstr="",tmpstr1="",tmpstr2="",tmpstr3="";
	            if(dataAccesshsh.containsKey(id)){
	            	tmpstr ="{name:'"+name+"',checked:true,id:'"+id+"'}";
	            }else{
	            	tmpstr ="{name:'"+name+"',id:'"+id+"'}";
	            }
	            if(result.indexOf("id:'"+parentId+"',nodes")!=-1){
	    			tmpstr1 =result.substring(0,result.indexOf("id:'"+parentId+"',nodes"));
	    			String str =result.substring(result.indexOf("id:'"+parentId+"',nodes"),result.length());
	    			tmpstr1 +=str.substring(0, str.indexOf("]"));
	    			tmpstr2 =","+tmpstr;
	    			tmpstr3 =str.substring(str.indexOf("]"),str.length());
	    		}else{
	    			tmpstr1 =result.substring(0,result.indexOf("id:'"+parentId+"'")+("id:'"+parentId+"'").length());
	        		tmpstr2 =",nodes:["+tmpstr+"]";
	        		tmpstr3 =result.substring(result.indexOf("id:'"+parentId+"'")+("id:'"+parentId+"'").length(),result.length());
	    		}
	    		result =tmpstr1+tmpstr2+tmpstr3;
	    		Mp.put(id, name);
	        }else{
	        	slist.add(data);
        	}
        }
        if(slist.size()>0){
        	result=getSubAllTree(slist,Mp,dataAccesshsh,result);
        }
		return result;
	}
	
	 
	/**
	 * 验证机构简称
	 * @throws IOException
	 */
	public void checkName() throws IOException {
		//机构简称
		System.out.println("验证机构简称");
		String abbreviation = "" ;
		try {
			HttpServletRequest request = getRequest();
			abbreviation=getRequest().getParameter("abbreviation");
			Map<String, Object> parameter = new HashMap<String, Object>();
			
			parameter.put("abbreviation", abbreviation);
			List list = dataorganizationsManager.findList(parameter);
			if(list!=null && list.size()>0){
				getResponse().getWriter().print(false);			
			}else{
				getResponse().getWriter().print(true);
		    }
		} catch (Exception e) {
			getResponse().getWriter().print(false);
			e.printStackTrace();
		}
	}
	/**
	 * 查询当前操作员机构信息
	 * @throws IOException
	 */
	public void getDataOrganizationsInfo() throws IOException {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			HttpServletRequest request = getRequest();
			// 从登录用户类中取当前用户信息
			//UserInfo userInfo = LogonUser.logonUser();
			//String id = userInfo.getCpId();

			DataOrganizations dataorganizationsobj = new DataOrganizations();
			dataorganizationsobj = dataorganizationsManager.getById("1");
			result.put("success", true);
			result.put("msg", dataorganizationsobj);

		} catch (Exception e) {
			e.printStackTrace();
			result.put("success", false);
			result.put("msg", "读取失败!");
			e.printStackTrace();
		}
		outJson(result);
	}
	/**
	 * 操作员 修改 个人信息
	 * 
	 * @throws IOException
	 */
	public void personal() throws IOException{
		Map<String, Object> result = new HashMap<String, Object>();
			try{
				HttpServletRequest request = getRequest();
				String jsonstring = request.getParameter("jsonstring");
				if (null != jsonstring&&!"".equals(jsonstring)) {
					JSONObject jsonobject =JSONObject.fromObject( jsonstring );
					DataOrganizations dataorganizationsobj = (DataOrganizations)JSONObject.toBean(jsonobject, DataOrganizations.class); 
					// 从登录用户类中取当前用户信息
					//UserInfo userInfo = LogonUser.logonUser();
					//String id = userInfo.getCpId();
					dataorganizationsobj.setId("1");
					dataorganizationsManager.personal(dataorganizationsobj);
					result.put("success", true);
					result.put("msg", "修改成功!");
				}else{
					result.put("success", false);
					result.put("msg", "修改失败 数据错误!");
				}
			}catch (Exception e){
				result.put("success", false);
				result.put("msg", "修改失败!");
				e.printStackTrace();
			}
		outJson(result);
	}
	
	/**
	 * 将ADC订购表中的机构代码与平台的机构代码关联
	 * 实现:修改平台组织机构表tg_data_organizations_info的机构代码(CP_CODE_)设为'订购表TP_EC_ORDER中EC编码(EC_ID)'
	 * @author bzq 2011-04-16
	 * @throws IOException
	 */
	public void match() throws IOException{
		Map<String, Object> result = new HashMap<String, Object>();
		try{
			HttpServletRequest request = getRequest();
			/**组织机构ID*/
			String ids = (null==request.getParameter("ids"))? "" : request.getParameter("ids");
			/**订购表中的EC编码*/
			String ecorderId = (null==request.getParameter("ecorderId"))? "" :request.getParameter("ecorderId");
			System.out.println("######~~!@# ids="+ids+",ecorderId="+ecorderId);
			if ((!"".equals(ids))&&(!"".equals(ecorderId))) {
				DataOrganizations dataorganizationsobj = dataorganizationsManager.getById(ids);
				dataorganizationsobj.setCpCode(ecorderId);
				/**机构信息是否同步:10-已经同步,20-未同步,将ADC机构代码写到cp_code_中,实现两边机构代码一致.*/
				dataorganizationsobj.setSyncCpCode("10");
				dataorganizationsManager.update(dataorganizationsobj);
				result.put("success", true);
				result.put("msg", "操作成功!");
			}else{
				result.put("success", false);
				result.put("msg", "操作失败 数据错误!");
			}
		}catch (Exception e){
			result.put("success", false);
			result.put("msg", "操作失败!");
			e.printStackTrace();
		}
		outJson(result);
	}
	
	
	/**
	 * 开通组织机构
	 *  写 组织机构一条数据,操作员表一条数据,组织机构数据权限表一条数据.
	 * @throws IOException
	 */
	public void dredge() throws IOException{
		Map<String, Object> result = new HashMap<String, Object>();
		try{
			HttpServletRequest request = getRequest();
			String dataorganizationsJson = request.getParameter("dataorganizationsJson");
			if (null != dataorganizationsJson&&!"".equals(dataorganizationsJson)) {
				JSONObject jsonobject =JSONObject.fromObject( dataorganizationsJson );
				DataOrganizations dataorganizationsobj = (DataOrganizations)JSONObject.toBean(jsonobject, DataOrganizations.class); 
				//System.out.println( dataorganizationsobj.getUser().getName());
				//System.out.println( dataorganizationsobj.getUserRole().getRoleIdStr());
				dataorganizationsManager.dredge(dataorganizationsobj);
				result.put("success", true);
				result.put("msg", "添加成功!");
			}else{
				result.put("success", false);
				result.put("msg", "添加失败 数据错误!");
			}
		}catch (Exception e){
			result.put("success", false);
			result.put("msg", "添加失败!");
			e.printStackTrace();
		}
		outJson(result);
	}
	
}
